package com.wlz.framework;

import com.wlz.framework.register.RemoteMapRegister;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 * @author wlz
 * @date 2022-07-11  9:33 下午
 */
public class ProxyFactory<T> {


    @SuppressWarnings("unchecked")
    public static <T> T getProxy(final Class interfaceClass) {
        return (T)Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // mock 功能
                String mock = System.getProperty("mock");
                if (mock != null && mock.startsWith("mock")) {
                    String result = mock.replace("return:", "");
                    return result;
                }

                try {
                    // 最初 实现
               /* HttpClient httpClient = new HttpClient();
                Invocation invocation = new Invocation(interfaceClass.getName(), method.getName(), method.getParameterTypes(), args);
                String result = httpClient.send("localhost", 8080, invocation);*/

                    // 改进 增加支持集群
                   /* List<URL> urls = RemoteMapRegister.get(interfaceClass.getName());
                    URL url = LoadBalance.random(urls);
                    HttpClient httpClient = new HttpClient();
                    Invocation invocation = new Invocation(interfaceClass.getName(), method.getName(), method.getParameterTypes(), args);
                    String result = httpClient.send(url.getHostname(), url.getPort(), invocation);*/

                   /* // 再改进
                    List<URL> urls = RemoteMapRegister.get(interfaceClass.getName());
                    URL url = LoadBalance.random(urls);
                    Protocol protocol = new HttpProtocol();
                    Invocation invocation = new Invocation(interfaceClass.getName(), method.getName(), method.getParameterTypes(), args);
                    String result = protocol.send(url, invocation);*/

                    // 再再改进
                    List<URL> urls = RemoteMapRegister.get(interfaceClass.getName());
                    URL url = LoadBalance.random(urls);
                    Protocol protocol = ProtocolFactory.getProtocol();
                    Invocation invocation = new Invocation(interfaceClass.getName(), method.getName(), method.getParameterTypes(), args);
                    String result = protocol.send(url, invocation);

                    return result;
                } catch (Exception e) {
                    return "sorry 执行出错 。。。";
                }
            }
        });

    }

}
